package org.chy.config;

import org.chy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;

/**
 * 认证服务器配置
 * @author  chenghy
 * @date    2018年01月15日 13时31分16秒
 * @Description 发上等愿,结中等缘,享下等福;向高处立,就平处坐,从宽处行.
 * @Package org.chy.config
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter  {
	private static String REALM = "MY_OAUTH_REALM";
	
	private @Autowired TokenStore tokenStore;
	private @Autowired AuthenticationManager authenticationManager;
	private @Autowired UserService userService;
	
	@Override
	public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
		clients.inMemory()
			   .withClient("my-trusted-client") //客户端ID
			   .authorizedGrantTypes("password","authorization_code","refresh_token","implicit")
			   .scopes("read","write","trust") //授权用户的操作权限
			   .secret("secret") //密码
			   .accessTokenValiditySeconds(6000);//token有效期为120秒
	}
	
	@Override
	public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
		endpoints
			.tokenStore(tokenStore)
			.authenticationManager(authenticationManager)
			.userDetailsService(userService);
	}
	
	@Override
	public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
		security.realm(REALM + "/client");
	}
}
